import 'dart:async';

import 'package:get/get.dart';
import 'package:high_help_apps/common/apis/v1/email.dart';
import 'package:high_help_apps/common/entities/misc/email/auth_email_request_entity.dart';
import 'package:high_help_apps/common/entities/misc/email/auth_email_response_entity.dart';
import 'package:high_help_apps/common/entities/misc/email/send_email_response_entity.dart';
import 'package:high_help_apps/common/entities/user/user_auth_entity.dart';
import 'package:high_help_apps/common/routes/app_pages.dart';
import 'package:high_help_apps/common/utils/toast.dart';
import '../../../global.dart';
import 'email_auth_state.dart';

class EmailAuthLogic extends GetxController {
  final state = EmailAuthState();

  int _currentTimer = 0;
  bool isSend = false;
  late Timer _timer;
  var sendButtonText = '发送'.obs;

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    clickSendButton();
    state.email = Get.arguments['email'];
    state.uid = Get.arguments['uid'] ?? -1;
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    _timer.cancel();
  }

  void sendEmail() async {
    toastInfo(msg: '发送邮件成功!');
    SendEmailResponseEntity sendEmailResponseEntity = await EmailAPI.send(state.email);
    state.emailToken = sendEmailResponseEntity.detail.token;
  }

  void clickSendButton() {
    if (isSend == true) return;
    isSend = true;
    _currentTimer = 60;
    sendEmail();
    _timer = Timer.periodic(Duration(milliseconds: 1000), (timer) {
      _currentTimer--;
      sendButtonText.value = '再次发送(剩余时间:$_currentTimer秒)';
      if (_currentTimer == 0) {
        isSend = false;
        _currentTimer = 0;
        sendButtonText.value = '再次发送';
        _timer.cancel();
      }
    });
  }

  // 验证邮箱的
  void authEmail(value) async {

    AuthEmailRequestEntity params = AuthEmailRequestEntity().fromJson({
      "token": state.emailToken,
      "uid": state.uid,
      "code": value
    });

    AuthEmailResponseEntity authEmailResponseEntity = await EmailAPI.auth(params: params);

    if (authEmailResponseEntity.success == true) {
      toastInfo(msg: '验证成功 😊');

      UserAuthEntity userProfile = UserAuthEntity(
          uid: state.uid,
          token: authEmailResponseEntity.detail.token
      );
      Global.saveAuth(userProfile);

      Future.delayed(Duration(milliseconds: 1000), () {
        Get.offAllNamed(AppRoutes.HOME_SCAFFOLD);
      });
    } else {
      toastInfo(msg: '验证码错误 😭');
    }
  }
}
